// pages/goodsdetails/goodsdetails.js
Page({
  data: {
    goodsDetail: {},
    swiperImages: [],
    isCollected: false,
  },
  onLoad: function(options) {
    const gid = options.gid;
    console.log('Received gid:', gid);
    const url = 'https://api-hmugo-web.itheima.net/api/public/v1/goods/detail/?goods_id=' + gid;
    console.log(url);
    wx.request({
      url: url,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.message) {
          const goodsDetail = res.data.message;
          goodsDetail.goods_introduce = goodsDetail.goods_introduce.replace(/\.webp/g, '.jpg');
          const swiperImages = goodsDetail.pics.map(pic => pic.pics_big);
          this.setData({
            goodsDetail: goodsDetail,
            swiperImages: swiperImages
          }, () => {
            this.loadCollectStatus();
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },
  previewImage: function(e) {
    var current = e.currentTarget.dataset.src;
    wx.previewImage({
      current: current,
      urls: this.data.swiperImages
    });
  },
  loadCollectStatus: function() {
    const goodsId = this.data.goodsDetail.goods_id;
    const collectList = wx.getStorageSync('collectList') || {};
    this.setData({
      isCollected: collectList[goodsId] || false
    });
  },
  toggleCollect: function() {
    const goodsId = this.data.goodsDetail.goods_id;
    let collectList = wx.getStorageSync('collectList') || {};
    let isCollected = !this.data.isCollected;
    this.setData({ isCollected });

    if (isCollected) {
      collectList[goodsId] = true;
    } else {
      delete collectList[goodsId];
    }
    wx.setStorageSync('collectList', collectList);
    wx.showToast({
      title: isCollected ? '收藏成功' : '取消收藏',
      icon: 'success',
      duration: 2000
    });
  },
  addToCart: function() {
    let cart = wx.getStorageSync('cart') || [];
    let goods = this.data.goodsDetail;
    goods.goods_id = goods.goods_id.toString();
    let exist = cart.find(item => item.goods_id === goods.goods_id);
    if (exist) {
      exist.goods_count += 1;
    } else {
      goods.goods_count = 1; 
      cart.push(goods);
    }
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '已加入购物车',
      icon: 'success',
      duration: 2000
    });
  },
})